package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Cart;
import model.DatabaseException;
import model.MiniCart;

/**
 * Servlet implementation class CartJSON
 */
@WebServlet("/CartJSON")
public class CartJSON extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		HttpSession session = request.getSession();
		MiniCart miniCart = MiniCart.get(session);

		Set<Integer> inventoryIds = miniCart.getInventoryIds();
		Map<Integer, Integer> quantities = miniCart.getQuantities();
		response.setContentType("application/json");
//		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();

		try {
			Cart cart = Cart.getCart(inventoryIds);
			cart.setQuantities(quantities);
			String json = Cart.getCartJson(cart);
			out.print(json);
		} catch (DatabaseException e) {
			out.print("{}");
		}

	}

}
